#include <iostream>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>

void ChildWrite(int fdw)
{
    // 向管道中不断写入数据
    char buffer[1024];
    int cnt = 15;
    while (true)
    {
        int n = snprintf(buffer, sizeof(buffer), "I am child,my pid is %d,cnt = %d", getpid(), cnt);
        cnt--;
        // 写入管道
        if (n > 0)
        {
            write(fdw, buffer, strlen(buffer));
        }
        sleep(1);
    }
}

void FatherRead(int fdr)
{
    // 从管道读取数据
    char buffer[1024];
    while (true)
    {
        // 清空一下buffer
        //buffer[0] = 0;
        int n = read(fdr, buffer, sizeof(buffer) - 1);
        buffer[n] = 0;
        if (n > 0)
        {
            std::cout << "child say:" << buffer << std::endl;
        }
    }
}

int main()
{
    // 1.父进程创建管道文件
    int fds[2] = {0};
    int n = pipe(fds);
    if (n < 0)
    {
        std::cerr << "pipe err:" << std::endl;
        return 1;
    }

    std::cout << "fds[0]:" << fds[0] << std::endl;
    std::cout << "fds[1]:" << fds[1] << std::endl;

    // 2.父进程创建子进程
    pid_t pid = fork();
    if (pid == 0)
    {
        // child
        // child->r father->w

        close(fds[0]);
        ChildWrite(fds[1]);

        close(fds[1]);
    }

    close(fds[1]);

    FatherRead(fds[0]);
    // 回收子进程
    waitpid(pid, NULL, 0);
    close(fds[0]);

    return 0;
}